﻿var MouseEventType = 
{
    MOUSE_MOVE : 1,
    MOUSE_DOWN : 2,
    MOUSE_UP : 3
}

var Mouse =
{
    IsInitialized : false,
    
    Observers : new Array(),
    
    Initialize : function()
    {
        if(!Mouse.IsInitialized)
        {
            document.onmousemove = Mouse.MouseMoveCallback;
            document.onmouseup = Mouse.MouseUpCallback;
            document.onmousedown = Mouse.MouseDownCallback;
            Mouse.IsInitialized = true;
        }
    },
    
    MouseMoveCallback : function(ev)
    {
        if(!document || !document.body) return;
        
        ev = ev || window.event;
        
        if(ev.pageX || ev.pageY)
        {
            Mouse.X = ev.pageX; Mouse.Y = ev.PageY;
        }
        else
        {
            var verticalScroll = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
            var horizontalScroll = document.documentElement ? document.documentElement.scrollLeft : document.body.scrollLeft;
            Mouse.X = ev.clientX + horizontalScroll - document.body.clientLeft;
            Mouse.Y = ev.clientY + verticalScroll - document.body.clientTop;
        }
        
        Mouse.NotifyObservers(MouseEventType.MOUSE_MOVE);
    },
    
    MouseUpCallback : function()
    {
        Mouse.ButtonState = false;
        Mouse.NotifyObservers(MouseEventType.MOUSE_UP);
    },

    MouseDownCallback : function()
    {
        Mouse.ButtonState = true;
        Mouse.NotifyObservers(MouseEventType.MOUSE_DOWN);
    },
                
    NotifyObservers : function(state)
    {
        Mouse.Observers.CallForEach
        (
            function(observer)
            {
                try { observer(Mouse.X, Mouse.Y, state); } catch(exp) { alert(exp.message); }
            }
        );
    },

    X: 0,
    Y: 0,
    ButtonState : false,
    
    Attach: function(callback)
    {
        Mouse.Observers.Add(callback);
    }
};


